package cn.nuc.edu.onlinestore.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.nuc.edu.onlinestore.entity.Goods;
import cn.nuc.edu.onlinestore.entity.Sysuser;
import cn.nuc.edu.onlinestore.service.interfaces.IGoodsService;
import cn.nuc.edu.onlinestore.util.PageControl;
import cn.nuc.edu.onlinestore.util.Pager;

/**
 * 处理前台的请求
 * @author 王凯
 *
 */
@Controller
public class FountHandler {

	/**
	 * 商品业务逻辑
	 */
	@Autowired
	private IGoodsService goodsService;
	
	/**
	 * 获取商品列表(前台)
	 */
	@RequestMapping("/index{index}")
	public ModelAndView listIndex(
			@RequestParam(value = "keyword", required = false) String keyword,
			@PathVariable(value = "index", required = false) Integer index,
			ModelAndView modelAndView,
			HttpSession session) {
		
		//查看是否有关键字
		String key = keyword;
		if (keyword != null) {
			key = "%" + keyword + "%";
			modelAndView.addObject("keyword", keyword);
		}
		
		//分页控制逻辑
		PageControl pc = new PageControl();
		Integer currindex = 1;
		if(index != null){
			currindex = index;
		}
		pc.setCurrentindex(currindex);
		pc.setPagesize(5);
		
		//前台过滤下架商品
		Pager<Goods> pager = goodsService.list(key, pc, true);
		
		Map<Goods, Integer> shoppingcart = 
				(Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		int goodscount = 0;
		Set<Goods> goodsSet = shoppingcart.keySet();
		for (Goods itergoods : goodsSet) {
			goodscount += shoppingcart.get(itergoods);
		}
		session.setAttribute("count", goodscount);
		
		modelAndView.addObject("pager", pager);
		modelAndView.setViewName("forward:/index.jsp");
		
		return modelAndView;
	}
	
	/**
	 * 获取商品信息(前台)
	 */
	@RequestMapping("/detail/{id}")
	public ModelAndView detail(
			@PathVariable(value = "id", required = false) Integer id,
			ModelAndView modelAndView,
			HttpSession session) {
		
		Goods goods = new Goods();
		goods.setGid(id);
		goods = goodsService.detail(goods);
		modelAndView.addObject("item", goods);
		
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		int goodscount = 0;
		Set<Goods> goodsSet = shoppingcart.keySet();
		for (Goods itergoods : goodsSet) {
			goodscount += shoppingcart.get(itergoods);
		}
		modelAndView.addObject("count", goodscount);
		
		modelAndView.setViewName("forward:/item.jsp");
		return modelAndView;
	}
	
	/**
	 * 将商品添加到购物车（如果不指定件数，默认为1件）
	 * @param id 商品id，通过url传送
	 * @param count 购买数量
	 * @param map
	 * @return
	 */
	@RequestMapping("/addToShoppingCart{id}")
	public String addToShoppingCart(
			@PathVariable("id") Integer id,
			@RequestParam(value = "count", required = false) Integer count,
			Map<String, Object> map,
			HttpSession session) {
		
		//默认的跳转位置
		String dist = "forward:/addsuccess.jsp";
		
		//得到商品的详细信息
		Goods goods = new Goods();
		goods.setGid(id);
		goods = goodsService.detail(goods);
		
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		if (count == null) {
			count = 1;
		}
		
		//有货才可以添加
		if (goods.getGcount() > 0) {
			if (shoppingcart.containsKey(goods)) {
				Integer oldcount = shoppingcart.get(goods);
				shoppingcart.put(goods, oldcount + count);
			} else {
				shoppingcart.put(goods, count);
			}
		}
		//如果没货就跳转到之前的页面
		else {
			dist = "forward:/item.jsp";
		}
		calculate(map, shoppingcart);
		map.put("item", goods);
		session.setAttribute("shoppingcart", shoppingcart);
		return dist;
	}

	/**
	 * 计算总金额和总数量
	 * @param map
	 * @param shoppingcart
	 */
	private void calculate(Map<String, Object> map, Map<Goods, Integer> shoppingcart) {
		double cost = 0;
		int goodscount = 0;
		Set<Goods> goodsSet = shoppingcart.keySet();
		for (Goods itergoods : goodsSet) {
			cost = cost + itergoods.getGprice() * shoppingcart.get(itergoods);
			goodscount += shoppingcart.get(itergoods);
		}
		map.put("cost", cost);
		map.put("count", goodscount);
	}
	
	/**
	 * 显示购物车
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/getShoppingCart")
	public String getShoppingCart(Map<String, Object> map,
			HttpSession session) {
		
		//获得购物车
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		//重新计算购物车中商品的数量
		calculate(map, shoppingcart);
		
		//重置session中的购物车
		session.setAttribute("shoppingcart", shoppingcart);
		
		return "forward:/cart.jsp";
	}
	
	/**
	 * 购物车中某类商品数量+1
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/addone{id}")
	public String addone(
			@PathVariable("id") Integer id,
			Map<String, Object> map,
			HttpSession session) {
		
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		double cost = 0;
		int goodscount = 0;
		Set<Goods> goodsSet = shoppingcart.keySet();
		for (Goods itergoods : goodsSet) {
			//找到商品
			if (id == itergoods.getGid()) {
				
				//查看用户之前要买多少
				Integer oldcount = shoppingcart.get(itergoods);
				
				//调出最新的库存信息
				Goods goods = new Goods();
				goods.setGid(id);
				goods = goodsService.detail(goods);
				
				//如果库存满足就给货，否则不给货
				if (oldcount < goods.getGcount()) {
					shoppingcart.put(itergoods, oldcount+1);
				}
			}
			
			//价格累计
			cost = cost + itergoods.getGprice() * shoppingcart.get(itergoods);
			
			//数量累计
			goodscount += shoppingcart.get(itergoods);
		}
		map.put("cost", cost);
		map.put("count", goodscount);
		
		session.setAttribute("shoppingcart", shoppingcart);
		
		return "forward:/cart.jsp";
	}
	
	/**
	 * 购物车中某一类商品数量-1
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/delone{id}")
	public String delone(
			@PathVariable("id") Integer id,
			Map<String, Object> map,
			HttpSession session) {
		
		//得到session中的购物车
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		double cost = 0;
		int goodscount = 0;
		Goods dist = null;
		Set<Goods> goodsSet = shoppingcart.keySet();
		
		Iterator<Goods> iterator = goodsSet.iterator();
		
		//迭代购物车重新核算价格
		while(iterator.hasNext()){
			Goods goods = iterator.next();
			
			//查出用户之前买了多少件商品
			Integer oldcount = shoppingcart.get(goods);
			
			//大于一件的商品数量-1
			if (oldcount > 1) {
				shoppingcart.put(goods, oldcount-1);
			} 
			//等于一件的相当于做删除
			else if(oldcount == 1) {
				dist = goods;
				continue;
			}
			
			//否则什么也不做
			
			//价格累计
			cost = cost + goods.getGprice() * shoppingcart.get(goods);
			
			//数量累计
			goodscount += shoppingcart.get(goods);
		}
		
		if (dist != null) {
			shoppingcart.remove(dist);
		}
		
		
		map.put("cost", cost);
		map.put("count", goodscount);
		
		//更新session中的购物车信息
		session.setAttribute("shoppingcart", shoppingcart);
		
		return "forward:/cart.jsp";
	}
	
	/**
	 * 删除购物车中的一种商品
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/del{id}")
	public String del(
			@PathVariable("id") Integer id,
			Map<String, Object> map,
			HttpSession session) {
		
		//得到session中的购物车
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		double cost = 0;
		int goodscount = 0;
		Goods dist = null;
		Set<Goods> goodsSet = shoppingcart.keySet();
		Iterator<Goods> iterator = goodsSet.iterator();
		while(iterator.hasNext()){
			Goods goods = iterator.next();
			if (id == goods.getGid()) {
				dist = goods;
				continue;
			}
			cost = cost + goods.getGprice() * shoppingcart.get(goods);
			goodscount += shoppingcart.get(goods);
		}
		
		
		if (dist != null) {
			shoppingcart.remove(dist);
		}
		
		map.put("cost", cost);
		map.put("count", goodscount);
		
		//将购物车放回session
		session.setAttribute("shoppingcart", shoppingcart);
		
		return "forward:/cart.jsp";
	}
	
	/**
	 * 购物车结算
	 * @param map
	 * @return
	 */
	@RequestMapping("/pay")
	public String pay(Map<String, Object> map,
			HttpSession session) {
		
		Map<Goods, Integer> shoppingcart = (Map<Goods, Integer>) session.getAttribute("shoppingcart");
		if (shoppingcart == null) {
			shoppingcart = new HashMap<>();
		}
		
		//取出session中存放的user
		Sysuser user = (Sysuser) session.getAttribute("user");
		
		//计算购物车所有商品的总价格
		double cost = 0;
		Set<Goods> goodsSet = shoppingcart.keySet();
		for (Goods itergoods : goodsSet) {
			double percost = itergoods.getGprice() * shoppingcart.get(itergoods);
			cost += percost;
			goodsService.addConsumerRecord(user, itergoods, shoppingcart.get(itergoods));
		}
		
		//保存总价格
		map.put("pay", cost);

		//更新购物车的功能
		session.removeAttribute("shoppingcart");
		
		//跳转到结算页面
		return "forward:/buysuccess.jsp";
	}
	
}
